package com.gxa.modules.service.impl;
import com.gxa.common.base.RespResult;
import com.gxa.common.constants.Constants;
import com.gxa.component.jwt.JwtUtil;
import com.gxa.modules.dto.LoginFormDTO;
import com.gxa.modules.mapper.EmployeeMapper;
import com.gxa.modules.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public RespResult login(LoginFormDTO loginFormDTO,HttpServletResponse response) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginFormDTO.getUsername(),loginFormDTO.getPassword());
            //登录
            subject.login(usernamePasswordToken);
            // 生成对应的Token
            String token =  JwtUtil.getToken(loginFormDTO.getUsername(),Constants.SECRENT,Constants.TOKEN_TTL);
            // 通过响应头返回给前端
            response.addHeader("token",token);
            return RespResult.success();
        }  catch (UnknownAccountException e){
            log.error("账户或密码有误");
            return RespResult.error("账户或密码有误");
        }catch (IncorrectCredentialsException e){
            log.error("账户或密码有误");
            return RespResult.error("账户或密码有误");
        }catch (LockedAccountException e){
            log.error("{}账户被冻结",loginFormDTO.getUsername());
            return RespResult.error("账户被冻结");
        }catch (AuthenticationException e){
            log.error("{}认证错误",loginFormDTO);
            return RespResult.error("认证错误");
        }
    }
}
